
import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:uuid/uuid.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ymt/api/apis.dart';
import 'package:ymt/db/offline_database_provider.dart';
import 'package:ymt/model/company.dart';
import 'package:ymt/model/token.dart';
import 'package:ymt/ui/login_form.dart';
import 'package:ymt/ui/main_page.dart';
import 'package:ymt/ui/sync.dart';
import 'package:ymt/utils/request.dart';

import '../utils/nav.dart';

class LoginPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return PageState();
  }
}

class PageState extends State<LoginPage>{

  static const String KEY_UUID = "installtion_uuid";
  var uuid;
  var qrText;
  int isAccountExpired = 0;
  int _pollMAX = 20;
  int _pollCounter = 0;
  bool noConnectivityWhenFirst = false;

  String _loginToken;

  SharedPreferences _pref;

  ConnectivityResult connectivityResult;



  @override
  void initState(){
    executeTask();
    super.initState();
  }

  executeTask() async {
    uuid = Uuid().v5(Uuid.NAMESPACE_URL, "ymt");
    print(uuid);
    //qrText = "http://nkjjq.cn/bd/$uuid";
    _pref = await SharedPreferences.getInstance();
    if(_pref.containsKey(KEY_UUID)){
      uuid = _pref.getString(KEY_UUID);
    }else{
      uuid = Uuid().v4();
      _pref.setString(KEY_UUID, uuid);
    }
    qrText = "http://nkjjq.cn/bd/$uuid";
    connectivityResult = await Connectivity().checkConnectivity();
    print(connectivityResult);
    if (connectivityResult == ConnectivityResult.none) {
      //无网络
      print("无网络");
      queryCompanyId();
    } else {
      print("有网络");
      getTokenWIthDeviceId(context, uuid);
    }
  }

  @override
  Widget build(BuildContext context) {

    if(noConnectivityWhenFirst){
      return new Center(child: Text("请连接网络"));
    }
    if(_pollCounter > _pollMAX){
      return new Center(child: RaisedButton(child: Text("点击重试"),color: Colors.blueGrey, onPressed: (){
        _pollCounter = 0;
        setState(() {});
        getTokenWIthDeviceId(context, uuid);
      },));
    }
    if(isAccountExpired != 0){
      return new Center(child: Text("账号已过期，请联系续费"));
    }else{
      var vertical = Column(children: [
        _buildQrImage(qrText),
        Text("请扫描二维码登录", style: TextStyle(color: Colors.black),)
      ], mainAxisAlignment: MainAxisAlignment.center,);
      Widget content = Container(child: vertical, width: MediaQuery
          .of(context)
          .size
          .width, color: Colors.white,);

      var bottomEnter = Container(alignment: Alignment.bottomCenter,
        child: click(Text("账号密码登录》", style: TextStyle(color: Colors.black),), (){
          Nav.destroyNav(context, LoginForm());
        }),
        margin: EdgeInsets.all(40),);
      return Stack(children: <Widget>[content, bottomEnter],);
    }
  }

  Widget click(child, onTap) {
    return GestureDetector(child: child, onTap: onTap,);
  }


  Widget _buildQrImage(text) {
    print("二维码链接：$text");
    if (text == null) {
      return Container(margin: EdgeInsets.all(15),
        decoration: BoxDecoration(border: Border.all()),
        width: 200,
        height: 200,);
    } else {
      var child = QrImage(data: qrText, size: 200, version: QrVersions.auto,);
      return Container(child: child, margin: EdgeInsets.all(15),);
    }
  }

  // 通过设备码获取登录token<轮训>
  getTokenWIthDeviceId(context, uuid) async {
    if(_pollCounter > _pollMAX){
      setState(() {});
      return;
    }
    _pollCounter++;

    try {
      Response response = await Request.dio().get(
          ApiPaths.LOGIN, queryParameters: {"installationid": uuid});
      Token result = Token.fromJson(response.data);
      if (result != null) {
        if (result.token != null) {
          _loginToken = result.token;
          //进入主页
          getCompanyWithToken(result.token);
        } else {
          Future.delayed(Duration(milliseconds: 300), () => getTokenWIthDeviceId(context, uuid));
        }
      }
    } on DioError catch(e){
      print(e);
      //轮训网络出错，监测本地是否有缓存，若有直接进入主界面
      setState(() {
        noConnectivityWhenFirst = true;
      });
    }
  }

  /// 通过Token获取公司信息
  getCompanyWithToken(token) async {
    var response = await Request.dio().get(ApiPaths.LOGIN, queryParameters: {"token": token});
    Company company = Company.fromJson(response.data);
    Request.dio().options.headers["token"] = company.jwt_token;//更新token
    checkAccountExpiredOnline(company.company_id);
  }

  // 检查是否过期
  checkAccountExpiredOnline(companyId) async {
    var response = await Request.dio().get(ApiPaths.COMPANY, queryParameters: {"id": companyId});
    var company = response.data[0];
    compareExpiredTime(company["deadline"], company["name"], company["id"]);
  }


  /// 从本地数据库查询公司信息
  queryCompanyId(){
    OfflineDatabaseProvider().open((Database db) async {
      List result = await db.query(OfflineDatabaseProvider.TABLE_COMPANIES);
      print(result);
      if(result != null){
        if(result.length > 0){
          Map company = result[0];
          if(company != null){
            if(company.containsKey("id")){
              var companyId = company["id"];
              if(companyId != null){
                if(companyId > 0){
                  /// yes
                   String companyDeadline = company["deadline"];
                   int companyId = company["id"];
                   String companyName = company["name"];
                   compareExpiredTime(companyDeadline, companyName, companyId);
                   return;
                }
              }
            }
          }
        }
      }
      setState(() {
        noConnectivityWhenFirst = true;
      });
      /// no
    });
  }

  void compareExpiredTime(String companyDeadline, String companyName, int companyId) {
    DateTime deadline = DateTime.parse(companyDeadline);
    DateTime current = DateTime.now();
    if (deadline.isBefore(current)){
      print("账号过期");
      setState(() {
        isAccountExpired = 1;
      });
    }else{
      /// 进入同步页面若无网络，就直接跳过主页，如果进入主页没有内容
      if(connectivityResult == ConnectivityResult.none){
        Nav.destroyNav(context, MainPage(companyId, companyName, _loginToken));
      }else{
        Nav.destroyNav(context, SyncPage(companyId, companyName, _loginToken));
      }
      print("账号未过期");
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}